package com.lili.backtrack;

import java.util.*;

/**
 * @Auther: 李 力
 * @Date: 2024/8/20
 * @Description: 组合总和
 * @version: 1.0
 */
public class LeetCode39 {
    public static List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<>();
        dfs(0, candidates, target, new LinkedList<>(), result);
        return result;
    }

    private static void dfs(int start, int[] candidates, int target, LinkedList<Integer> stack, List<List<Integer>> result) {
        if (target < 0) {
            return;
        }
        if (target == 0) {
            result.add(new ArrayList<>(stack));
            return;
        }
        for (int i = start; i < candidates.length; i++) {
            if (target < candidates[i]) {
                continue;
            }
            stack.push(candidates[i]);
            dfs(i, candidates, target - candidates[i], stack, result);
            stack.pop();
        }
    }
}
